/*
 * Copyright@www.it1997.com.
 * @Author: 陈晓晨
 * @Date: 2020/6/22
 * Description:版权所有 QQ:376231445
 */

package com.it1997.it1997admin.handler;

import com.it1997.it1997admin.configuration.MyUserDetailService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@Log4j2
public class MyAuthenticationProvide implements AuthenticationProvider {
    @Autowired
    private MyUserDetailService userDetailService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        UserDetails userDetails = userDetailService.loadUserByUsername(username);
        if(userDetails==null){
            log.info("用户名不存在！");
            throw new BadCredentialsException("用户名不存在");

        }
        if(!passwordEncoder.matches(password,userDetails.getPassword())){
            log.info("密码错误！");
            throw new BadCredentialsException("密码错误");
        }

        /*用户名密码认证成功*/
        return new UsernamePasswordAuthenticationToken(userDetails,password,userDetails.getAuthorities());

    }

    @Override
    public boolean supports(Class<?> authentication) {
        return false;
    }

}
